using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text.RegularExpressions;

namespace GoldStone.Common.Utils {
    public class RegexTypeConverter : TypeConverter {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
            if (sourceType == typeof (string)) {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
            if (value is string) {
                return new Regex(value as string);
            }
            return base.ConvertFrom(context, culture, value);
        }
    }


    public static class RegexUtil {
        public static String FirstMatch(String content, Regex regex, String variant) {
            return FirstMatch(content, regex, variant, "");
        }

        public static String FirstMatch(String content, Regex regex, String variant, String defaultValue) {
            foreach (Match m in regex.Matches(content)) {
                return m.Groups[variant].Value.Trim();
            }
            return defaultValue;
        }

        public static String FirstMatch(String content, Regex[] regexes, String variant, String defaultValue) {
            foreach (Regex regex in regexes) {
                string result = FirstMatch(content, regex, variant);
                if (result != "") {
                    return result;
                }
            }
            return defaultValue;
        }

        public static String FirstMatch(String content, IList<Converter<String, String>> converters, String defaultValue) {
            foreach (Converter<string, string> converter in converters) {
                String result = converter(content);
                if (result != "") {
                    return result;
                }
            }
            return defaultValue;
        }

        public static List<String> AllMatches(String content, Regex regex, String variant) {
            List<String> result = new List<string>();
            foreach (Match m in regex.Matches(content)) {
                result.Add(m.Groups[variant].Value.Trim());
            }
            return result;
        }

        public static String RemoveAllMatches(String content, Regex regex) {
            return regex.Replace(content, "");
        }

//        public static Regex EmailRegex = new Regex( "(?<Stub>[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+)" );
        public static Regex EmailRegex = new Regex( "(?<Stub>[a-zA-Z0-9_\\-]{1,}@[a-zA-Z0-9_\\-]{1,}\\.[a-zA-Z0-9_\\-.]{1,})" );
    }
}